<script lang="ts" setup>
import type {
  ClassInfo,
  ClassTabType,
  AddClassFormData,
  TeacherInfo,
} from '@/types/class/class';
import { NButton, NSelect, NTabs, NTabPane, useThemeVars } from 'naive-ui';
import { computed, onMounted, ref } from 'vue';
import { getClassList, addClass, deleteClass } from '@/api/myclass/myclass';
import { getTeacher } from '@/api/user/user';
import { useClipboard } from '@vueuse/core';

// 获取Naive UI主题变量
const themeVars = useThemeVars();

const tabs = [
  { value: 'intro', label: '全部' },
  { value: 'managed', label: '我管理的' },
  { value: 'joined', label: '我加入的' },
] as const;

const classList = ref<ClassInfo[]>([]);
const activeTab = ref<ClassTabType>('intro');
const showDeleteConfirm = ref(false);
const showAddClassDialog = ref(false);
const teacherList = ref<{ label: string; value: string }[]>([]);
const selectedCover = ref(0);
const selectedClassIds = ref<number[]>([]);

const formData = ref<Omit<ClassInfo, 'class_id'> & { otherTeacher: string[] }>({
  class_name: '',
  number_now: 0,
  number_max: 30, // 默认最大人数
  teacher: '',
  course_name: '',
  invitation_code: '',
  remark: '',
  class_cover_url: '',
  otherTeacher: [],
});

const hasSelectedClasses = computed(() => selectedClassIds.value.length > 0);

// 获取班级列表
const fetchClassList = async () => {
  try {
    const type = tabs.findIndex((tab) => tab.value === activeTab.value);
    const res = await getClassList(type);
    classList.value = res.data;
  } catch (error) {
    console.error('获取班级列表失败:', error);
  }
};

// 获取教师列表
const fetchTeachers = async () => {
  try {
    const res = await getTeacher();
    teacherList.value = res.data.map((teacher: TeacherInfo) => ({
      label: `${teacher.nickname} - ${teacher.faculty}`,
      value: teacher.username,
      faculty: teacher.faculty,
    }));
  } catch (error) {
    console.error('获取教师列表失败:', error);
  }
};

// 复制邀请码功能
const copyInviteCode = (code: string) => {
  const { copy } = useClipboard();
  copy(code).then(() => {
    window.$message?.success('邀请码已复制');
  });
};

// 处理标签页切换
const handleTabChange = (value: ClassTabType) => {
  activeTab.value = value;
  fetchClassList();
};

// 处理新增班级
const handleAddClasseConfirm = async () => {
  try {
    const submitData: AddClassFormData = {
      className: formData.value.class_name,
      otherTeacher: formData.value.otherTeacher,
      tea_type: 'username',
      classImg: `${selectedCover.value}`,
      classStudengNum: formData.value.number_max,
      remark: formData.value.remark || '',
    };

    await addClass(submitData);
    await fetchClassList();
    window.$notification?.success({ title: `${submitData.className} 云端教室已激活！AI+教育，让学习没有边界 🚀`, duration: 2500 });
    showAddClassDialog.value = false;
    formData.value = {
      class_name: '',
      number_now: 0,
      number_max: 30,
      teacher: '',
      course_name: '',
      invitation_code: '',
      remark: '',
      class_cover_url: '',
      otherTeacher: [],
    };
  } catch (error) {
    console.error('新增班级失败:', error);
  }
};

// 处理删除班级
const handleDeleteClasses = async () => {
  try {
    await deleteClass(selectedClassIds.value);
    await fetchClassList();
    window.$notification?.success({ title: '班级已被移除', duration: 2500 });
    showDeleteConfirm.value = false;
    selectedClassIds.value = [];
  } catch (error) {
    console.error('删除班级失败:', error);
  }
};

// 选择封面
const selectCover = (index: number) => {
  selectedCover.value = index;
  formData.value.class_cover_url = `cover_${index}`;
};

// 选择班级
const toggleClassSelection = (classId: number) => {
  const index = selectedClassIds.value.indexOf(classId);
  if (index > -1) {
    selectedClassIds.value.splice(index, 1);
  } else {
    selectedClassIds.value.push(classId);
  }
};

// 封面背景颜色函数
function getCoverBg(index: string) {
  const colors = [
    'linear-gradient(45deg, #06c399, #16a7c9, #2788fb)',
    'linear-gradient(135deg, #7e84f3, #757bf0, #545be5)',
    'linear-gradient(135deg, #482de7, #5b73fd, #5b7cfd)',
    'linear-gradient(135deg, #ffa123, #fe7710, #fd5e05)',
  ];
  return colors[Number(index)];
}

onMounted(async () => {
  await fetchClassList();
  await fetchTeachers();
});
</script>

<template>
  <div class="class-management">
    <div class="management-card">
      <div class="header-area">
        <div class="header-content">
          <div class="title-wrapper">
            <h2 class="modern-title"><icon-mdi:account-group />班级管理</h2>
          </div>
          <div class="actions">
            <n-button type="primary" @click="showAddClassDialog = true">
              新增班级
            </n-button>
            <n-button
              type="error"
              dashed
              :disabled="!hasSelectedClasses"
              @click="showDeleteConfirm = true"
            >
              解散班级
            </n-button>
          </div>
        </div>
        <div class="background-image">
          <img src="@/assets/images/courses/background.png" alt="background" />
        </div>
      </div>

      <n-tabs
        default-value="intro"
        class="class-tabs"
        @update:value="handleTabChange"
      >
        <n-tab-pane
          v-for="tab in tabs"
          :key="tab.value"
          :name="tab.value"
          :tab="tab.label"
        >
          <div class="class-list">
            <div
              v-for="classItem in classList"
              :key="classItem.class_id"
              class="class-card"
              :class="{
                selected: selectedClassIds.includes(classItem.class_id),
              }"
            >
              <div
                class="cover"
                :style="{ background: getCoverBg(classItem.class_cover_url) }"
                @click="toggleClassSelection(classItem.class_id)"
              >
                <div class="cover-overlay"></div>
                <span class="cover-text">{{ classItem.class_name }}</span>
              </div>
              <div class="info">
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                  "
                >
                  <div class="f-c-c gap-4">
                    <icon-mdi:account-tie-hat />
                    <p class="teacher">{{ classItem.teacher }}</p>
                  </div>
                  <div class="f-c-c gap-4">
                    <icon-mdi:account-child />
                    <span class="students" style="font-size: 13px"
                      >{{ classItem.number_now }}人</span
                    >
                  </div>
                </div>
                <div class="meta">
                  <n-button size="small">查看</n-button>
                  <div class="f-c-c" style="gap: 5px">
                    <!-- <div class="modify">管理</div> -->
                    <span class="invite-code" v-if="classItem.invitation_code">
                      邀请码: {{ classItem.invitation_code }}
                    </span>
                    <icon-mdi:content-copy
                      style="margin-top: 2px"
                      @click.stop="copyInviteCode(classItem.invitation_code)"
                    />
                  </div>
                </div>
              </div>
              <div
                class="checkbox"
                :class="{
                  checked: selectedClassIds.includes(classItem.class_id),
                }"
                @click="toggleClassSelection(classItem.class_id)"
              >
                <div class="check-icon"></div>
              </div>
            </div>
          </div>
        </n-tab-pane>
      </n-tabs>
    </div>

    <!-- 原生模态框实现 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click.self="showDeleteConfirm = false">
      <div class="modal-container">
        <div class="modal-header">
          <h3>解散班级</h3>
        </div>
        <div class="modal-body">
          <p>确认要解散选中的班级吗？</p>
        </div>
        <div class="modal-footer">
          <n-button @click="showDeleteConfirm = false">取消</n-button>
          <n-button type="error" @click="handleDeleteClasses">确认</n-button>
        </div>
      </div>
    </div>

    <!-- 新增班级对话框 -->
    <div v-if="showAddClassDialog" class="modal-overlay" @click.self="showAddClassDialog = false">
      <div class="modal-container">
        <div class="modal-header">
          <h3>新增班级</h3>
        </div>
        <div class="modal-body">
          <div class="class-info">
            <div class="form-item">
              <label>班级名称：</label>
              <input
                v-model="formData.class_name"
                placeholder="请输入班级名称"
              />
            </div>
            <div class="form-item">
              <label>相关教师：</label>
              <n-select
                v-model:value="formData.otherTeacher"
                placeholder="请选择相关教师"
                :options="teacherList"
                clearable
                multiple
                filterable
              />
            </div>
            <div class="form-item">
              <label>班级封面：</label>
              <div class="cover-grid">
                <div
                  v-for="(cover, index) in 4"
                  :key="index"
                  class="cover-item"
                  :class="{ active: selectedCover === index }"
                  @click="selectCover(index)"
                >
                  <span>{{
                    ['默认封面', '紫色封面', '深蓝封面', '橙色封面'][index]
                  }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <n-button @click="showAddClassDialog = false">取消</n-button>
          <n-button type="primary" @click="handleAddClasseConfirm"
            >确认</n-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.class-management {
  padding: 16px;
  height: 100%;

  .management-card {
    border-radius: 8px;
    padding: 25px;
    height: 100vh;
    background-color: v-bind('themeVars.bodyColor');
    box-shadow: v-bind('themeVars.boxShadow1');
  }
}

/* 头部区域样式 */
.header-area {
  display: flex;
  justify-content: space-between;

  .header-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    gap: 12px;

    .modern-title {
      font-size: 20px;
      font-weight: 500;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 8px;
      color: v-bind('themeVars.textColor1');

      .icon {
        width: 20px;
        height: 20px;
      }
    }

    .actions {
      display: flex;
      gap: 12px;
    }
  }

  .background-image {
    width: 280px;
    height: 154px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      // filter: v-bind('themeVars.iconColorFilter');
    }
  }
}

/* 班级列表样式 */
.class-list {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  margin-top: 15px;
  padding-bottom: 5px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background-color: v-bind('themeVars.modalColor');
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  box-shadow: v-bind('themeVars.boxShadow2');
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid v-bind('themeVars.dividerColor');

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 500;
    color: v-bind('themeVars.textColor1');
  }
}

.modal-body {
  padding: 24px;

  p {
    color: v-bind('themeVars.textColor2');
  }
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid v-bind('themeVars.dividerColor');
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单样式 */
.class-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;

  label {
    color: v-bind('themeVars.textColor1');
    font-size: 14px;
  }

  input {
    padding: 8px 12px;
    border: 1px solid v-bind('themeVars.borderColor');
    border-radius: 4px;
    background-color: v-bind('themeVars.inputColor');
    color: v-bind('themeVars.textColor1');

    &:focus {
      border-color: v-bind('themeVars.primaryColor');
      outline: none;
    }
  }
}

.class-card {
  position: relative;
  width: 260px;
  border-radius: 8px;
  overflow: hidden;
  background-color: v-bind('themeVars.cardColor');
  box-shadow: v-bind('themeVars.boxShadow1');
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    box-shadow: v-bind('themeVars.boxShadow2');
  }

  &.selected {
    box-shadow: 0 0 0 2px v-bind('themeVars.primaryColor');
  }

  .cover {
    position: relative;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-size: cover;
    background-position: center;

    .cover-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }

    .cover-text {
      position: relative;
      color: white;
      font-size: 18px;
      font-weight: bold;
      text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
      padding: 0 12px;
      text-align: center;
      z-index: 1;
    }
  }

  .info {
    padding: 12px;

    .title {
      margin: 0 0 8px;
      font-size: 16px;
      font-weight: 600;
      color: v-bind('themeVars.textColor1');
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .teacher,
    .course {
      margin: 4px 0;
      font-size: 13px;
      color: v-bind('themeVars.textColor3');
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .meta {
      display: flex;
      justify-content: space-between;
      margin-top: 8px;
      font-size: 12px;

      .students {
        color: v-bind('themeVars.textColor2');
      }

      .invite-code {
        color: v-bind('themeVars.primaryColor');
        font-weight: 500;
      }
    }
  }

  .checkbox {
    position: absolute;
    top: 8px;
    right: 8px;
    width: 20px;
    height: 20px;
    border-radius: 4px;
    border: 2px solid v-bind('themeVars.borderColor');
    background-color: v-bind('themeVars.baseColor');
    transition: all 0.2s;

    &.checked {
      background-color: v-bind('themeVars.primaryColor');
      border-color: v-bind('themeVars.primaryColor');

      .check-icon {
        display: block;
      }
    }

    .check-icon {
      display: none;
      position: absolute;
      left: 50%;
      top: 50%;
      width: 12px;
      height: 8px;
      border-left: 2px solid white;
      border-bottom: 2px solid white;
      transform: translate(-50%, -60%) rotate(-45deg);
    }
  }
}

/* 封面选择样式 */
.cover-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.cover-item {
  height: 100px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
  overflow: hidden;

  span {
    color: white;
    font-size: 14px;
    font-weight: 500;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
    z-index: 1;
  }

  &:hover {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }

  &.active {
    border: 2px solid v-bind('themeVars.primaryColor');
    box-shadow: v-bind('themeVars.primaryColor');
  }

  &:nth-child(1) {
    background: linear-gradient(45deg, #06c399, #16a7c9, #2788fb);
  }
  &:nth-child(2) {
    background: linear-gradient(135deg, #7e84f3, #757bf0, #545be5);
  }
  &:nth-child(3) {
    background: linear-gradient(135deg, #482de7, #5b73fd, #5b7cfd);
  }
  &:nth-child(4) {
    background: linear-gradient(135deg, #ffa123, #fe7710, #fd5e05);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-area {
    flex-direction: column;

    .background-image {
      width: 100%;
      margin-top: 16px;
    }
  }

  .cover-grid {
    grid-template-columns: 1fr;
  }
}
</style>
